package com.gitee.hljdrl.dialog.visitor;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.LayoutRes;
import androidx.annotation.StringRes;
import androidx.annotation.StyleRes;

import com.gitee.hljdrl.dialog.R;
import com.gitee.hljdrl.dialog.basis.DialogEvent;
import com.gitee.hljdrl.dialog.basis.OnEventListener;
import com.gitee.hljdrl.dialog.basis.OnVisitedListener;
import com.gitee.hljdrl.dialog.basis.ViewPartVisitor;
import com.gitee.hljdrl.dialog.util.UIUtil;


public abstract class BasisViewPartVisitor implements ViewPartVisitor, View.OnClickListener {

    protected String TAG = getClass().getSimpleName();
    private Dialog mDialog;
    private DialogEvent mDialogEvent;
    private View mView;
    protected OnVisitedListener mOnVisitedListener;
    private boolean mDismiss = false;
    protected boolean mCancelable = false;
    protected boolean mCanceledOnTouchOutside;
    protected long mMinimumTime = 0;
    protected long mShowTime = 0;
    protected long mTimeDismiss = 0;
    protected Context mContext;
    protected int mGravity = Gravity.NO_GRAVITY;
    protected int mLayout;
    protected @StyleRes int mDialogTheme;
    protected CharSequence mTitle;
    protected @StyleRes int mTitleTextAppearance;
    //------------------------------------------
    protected int mAutoLink = 0;
    //------------------------------------------
    protected int mContentGravity = Gravity.CENTER;
    protected CharSequence mContentText;
    protected CharSequence mLeftText;
    protected CharSequence mRightText;
    protected OnEventListener onEventListener;

    public BasisViewPartVisitor(Context context) {
        this.mContext = context;
    }

    protected final Context getContext() {
        return this.mContext;
    }

    @Override
    public final void setGravity(int gravity) {
        this.mGravity = gravity;
    }

    @Override
    public final int getGravity() {
        return this.mGravity;
    }

    @Override
    public void setTitle(String title) {
        this.mTitle = title;
    }

    @Override
    public void setTitle(CharSequence title) {
        this.mTitle = title;
    }

    @Override
    public void setTitle(@StringRes int titleId) {
        this.mTitle = getContext().getString(titleId);
    }

    /**
     * 设置content内容中超连接点击是否支持跳转.
     *
     * @param autoLink
     */
    public final void setAutoLink(int autoLink) {
        this.mAutoLink = autoLink;
    }

    public final void setContent(@StringRes int content) {
        this.mContentText = getContext().getString(content);
    }

    public final void setContent(String content) {
        this.mContentText = content;
    }

    public final void setContent(CharSequence content) {
        this.mContentText = content;
    }

    public final void setLeftText(String label) {
        this.mLeftText = label;
    }

    public final void setLeftText(@StringRes int label) {
        this.mLeftText = getContext().getText(label);
    }

    public final void setRightText(String label) {
        this.mRightText = label;
    }

    public final void setRightText(@StringRes int label) {
        this.mRightText = getContext().getText(label);
    }

    public final void setContentGravity(int gravity) {
        this.mContentGravity = gravity;
    }

    @Override
    public void setTitleTextAppearance(@StyleRes int style) {
        mTitleTextAppearance = style;
    }

    @Override
    public final void setLayout(@LayoutRes int layout) {
        mLayout = layout;
    }

    @Override
    public final void setOnEventListener(OnEventListener onEventListener) {
        this.onEventListener = onEventListener;
    }

    protected final OnEventListener getOnEventListener() {
        return onEventListener;
    }

    @Override
    public final int getLayout() {
        return mLayout;
    }

    @Override
    public void setDialogTheme(int theme) {
        this.mDialogTheme = theme;
    }

    public int getDialogTheme() {
        return mDialogTheme;
    }

    public void setCancelable(boolean mCancelable) {
        this.mCancelable = mCancelable;
    }

    public void setCanceledOnTouchOutside(boolean mCanceledOnTouchOutside) {
        this.mCanceledOnTouchOutside = mCanceledOnTouchOutside;
    }

    public boolean isDismiss() {
        return mDismiss;
    }

    @Override
    public final ViewPartVisitor setOnVisitedListener(OnVisitedListener visitedListener) {
        this.mOnVisitedListener = visitedListener;
        return null;
    }

    protected View getView() {
        return mView;
    }

    @Override
    public void onViewVisit(Dialog dialog, View view) {
        mView = view;
        mDialog = dialog;
        if (enablePromptVisit()) {
            try {
                onPromptViewVisit(dialog, view);
            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e(TAG, "error " + Log.getStackTraceString(ex));
            }
        }
        mDialog.setCancelable(mCancelable);
        mDialog.setCanceledOnTouchOutside(mCanceledOnTouchOutside);
        if (mOnVisitedListener != null) {
            mOnVisitedListener.onVisited(dialog, view);
        }
    }

    @Override
    public void onViewVisit(DialogEvent dialogEvent, View view) {
        mView = view;
        mDialogEvent = dialogEvent;
        if (enablePromptVisit()) {
            try {
                onPromptViewVisit(dialogEvent, view);
            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e(TAG, "error " + Log.getStackTraceString(ex));
            }
        }
        mDialog.setCancelable(mCancelable);
        mDialog.setCanceledOnTouchOutside(mCanceledOnTouchOutside);
        if (mOnVisitedListener != null) {
            mOnVisitedListener.onVisited(dialogEvent, view);
        }
    }

    protected boolean enablePromptVisit() {
        return true;
    }

    protected void onContentTextView(TextView textView, CharSequence contentText) {
        if (contentText != null) {
            textView.setText(contentText);
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        }
        if (mAutoLink != 0) {
            textView.setAutoLinkMask(mAutoLink);
        }
        textView.setGravity(mContentGravity);
    }

    protected final void onPromptViewVisit(Dialog dialog, View view) {
        final Context context = dialog.getContext();
        TextView mTvTitle = view.findViewById(R.id.dialog_tv_title);
        TextView mTvContent = view.findViewById(R.id.dialog_tv_content);
        TextView mBtnLeft = view.findViewById(R.id.dialog_btn_left);
        TextView mBtnRight = view.findViewById(R.id.dialog_btn_right);
        //-----------------------------------------------------------
        if (mTvTitle != null) {
            mTvTitle.setText(mTitle);
        }
        if (mTvContent != null) {
            onContentTextView(mTvContent, mContentText);
        }
        // 2. 优化按钮逻辑：仅当左右按钮均非空时处理
        if (mBtnLeft != null && mBtnRight != null) {
            // 设置按钮文本和点击事件
            mBtnLeft.setText(mLeftText);
            mBtnRight.setText(mRightText);
            mBtnLeft.setOnClickListener(this);
            mBtnRight.setOnClickListener(this);

            // 3. 统一处理可见性与背景
            boolean hasLeftText = !TextUtils.isEmpty(mLeftText);
            boolean hasRightText = !TextUtils.isEmpty(mRightText);

            if (hasLeftText && hasRightText) {
                // 双按钮均显示
                mBtnLeft.setVisibility(View.VISIBLE);
                mBtnRight.setVisibility(View.VISIBLE);
                mBtnLeft.setBackgroundResource(R.drawable.dialog_btn_left_selector); // 恢复默认背景
            } else if (hasLeftText || hasRightText) {
                // 单按钮显示：优先左按钮，若无左则用右按钮替代
                TextView visibleButton = hasLeftText ? mBtnLeft : mBtnRight;
                visibleButton.setVisibility(View.VISIBLE);
                visibleButton.setBackgroundResource(R.drawable.dialog_btn_center_selector);
                TextView hiddenButton = hasLeftText ? mBtnRight : mBtnLeft;
                hiddenButton.setVisibility(View.GONE);
            } else {
                // 无按钮文本时隐藏所有按钮
                mBtnLeft.setVisibility(View.GONE);
                mBtnRight.setVisibility(View.GONE);
            }
        }
    }

    protected final void onPromptViewVisit(DialogEvent dialogEvent, View view) {
        final Context context = dialogEvent.getContext();
        TextView mTvTitle = view.findViewById(R.id.dialog_tv_title);
        TextView mTvContent = view.findViewById(R.id.dialog_tv_content);
        TextView mBtnLeft = view.findViewById(R.id.dialog_btn_left);
        TextView mBtnRight = view.findViewById(R.id.dialog_btn_right);
        //-----------------------------------------------------------
        if (mTvTitle != null) {
            mTvTitle.setText(mTitle);
        }
        if (mTvContent != null) {
            onContentTextView(mTvContent, mContentText);
        }
        if (mBtnLeft != null && mBtnRight != null) {
            mBtnLeft.setText(mLeftText);
            mBtnRight.setText(mRightText);
            //-------------------------------------------------------------------------
            mBtnLeft.setOnClickListener(this);
            mBtnRight.setOnClickListener(this);
            //-------------------------------------------------------------------------
            if (!TextUtils.isEmpty(mLeftText) && !TextUtils.isEmpty(mRightText)) {
                mBtnLeft.setVisibility(View.VISIBLE);
                mBtnRight.setVisibility(View.VISIBLE);
            } else if (TextUtils.isEmpty(mLeftText) && TextUtils.isEmpty(mRightText)) {
                mBtnLeft.setBackgroundResource(R.drawable.dialog_btn_center_selector);
                mLeftText = context.getString(R.string.dialog_ui_action_ok);
                mBtnLeft.setText(mLeftText);
                mBtnRight.setVisibility(View.GONE);
            } else {
                if (TextUtils.isEmpty(mLeftText)) {
                    mBtnLeft.setBackgroundResource(R.drawable.dialog_btn_center_selector);
                    mBtnRight.setVisibility(View.GONE);
                } else if (TextUtils.isEmpty(mRightText)) {
                    mBtnLeft.setBackgroundResource(R.drawable.dialog_btn_center_selector);
                    mBtnRight.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        OnEventListener listener = getOnEventListener();
        try {
            if (id == R.id.dialog_btn_left) {
                if (listener != null) {
                    listener.onItemClick(true, getDialog());
                } else {
                    UIUtil.dismissDialog(getDialog());
                }
            } else if (id == R.id.dialog_btn_right) {
                if (listener != null) {
                    listener.onItemClick(false, getDialog());
                } else {
                    UIUtil.dismissDialog(getDialog());
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public final Dialog getDialog() {
        return mDialog;
    }

    public final DialogEvent getDialogEvent() {
        return mDialogEvent;
    }

    @Override
    public void onShow() {
        mShowTime = System.currentTimeMillis();
    }

    @Override
    public boolean onDismiss(Dialog dialog) {
        mDismiss = true;
        return false;
    }

    public ViewPartVisitor setMinimumTime(long time) {
        this.mMinimumTime = time;
        return this;
    }

    @Override
    public long getMinimumTime() {
        return this.mMinimumTime;
    }

    protected abstract Dialog createDialog(Context context, int theme);

    @Override
    public final Dialog apply() {
        Dialog dialog = createDialog(getContext(), getDialogTheme());
        return dialog;
    }

    @Override
    public final Dialog apply(int theme) {
        Dialog dialog = createDialog(getContext(), theme);
        return dialog;
    }

    @Override
    public final Dialog show() {
        Dialog dialog = createDialog(getContext(), getDialogTheme());
        dialog.show();
        return dialog;
    }

    @Override
    public final Dialog show(int theme) {
        Dialog dialog = createDialog(getContext(), theme);
        dialog.show();
        return dialog;
    }
}
